package com.yunxi.interceptor;

import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.rpc.RpcContext;
import org.jboss.logging.MDC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by xuruzi on 2019/3/7.
 *
 * 分布式日志,当前链路唯一标识
 *
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    @Value("${spring.application.name}")
    String applicationName;
    final String serverHost = NetUtils.getLocalHost();//当前服务器IP

    //在请求处理之前进行调用（Controller方法调用之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 分布式日志,记录当前请求唯一标识,当前处理服务器IP,和当前应用名
         */
//        Map<String,String> attachments = new HashMap<String,String>();
//        attachments.put("traceId",UUID.randomUUID().toString());//链路唯一标识
//        attachments.put("serverHost",serverHost);//当前服务器IP
//        attachments.put("applicationName", applicationName);//应用名称
//        RpcContext.getContext().setAttachments(attachments);
        RpcContext.getContext().setAttachment("traceId", UUID.randomUUID().toString());
        RpcContext.getContext().setAttachment("serverHost",serverHost);
        RpcContext.getContext().setAttachment("applicationName", applicationName);

        MDC.put("traceId", RpcContext.getContext().getAttachment("traceId"));
        MDC.put("serverHost",serverHost);
        MDC.put("applicationName",applicationName);
        return true;
    }

    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //在整个请求结束之后被调用，也就是在DispatcherServlet
    // 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
